package org.hj.modules.generatecode.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import freemarker.template.Template;
import org.hj.modules.generatecode.entity.ViewModule;
import org.hj.modules.generatecode.entity.ViewUiproperties;
import org.hj.modules.generatecode.service.IViewModuleService;
import org.hj.modules.generatecode.service.IViewUipropertiesService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gbw
 * 2020/7/5
 */

public class CodeGenerateUtils {

/*
    @Autowired
    private IViewUipropertiesService viewUipropertiesService;
    @Autowired
    private IViewModuleService viewModuleService;


   // private final String AUTHOR = "hj";
    //private final String CURRENT_DATE = "";
  //  private final String tableName = "sys_user";
  //  private final String packageName = "com.hj.aaa";
  //  private final String tableAnnotation = "质量问题";
   // private final String URL = "jdbc:mysql://localhost:3306/hj?useUnicode=true&characterEncoding=utf8";
  //  private final String USER = "root";
    //private final String PASSWORD = "root";
   // private final String DRIVER = "com.mysql.jdbc.Driver";
    private final String diskPath = "D://abc//";
  //  private final String changeTableName = replaceUnderLineAndUpperCase(tableName);

   */
/* public Connection getConnection() throws Exception {
        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
        return connection;
    }*//*


    public static void main(String[] args) throws Exception {
        CodeGenerateUtils codeGenerateUtils = new CodeGenerateUtils();
        codeGenerateUtils.generate("sys_user");
    }

    public void generate(String tableName) throws Exception {
        try {
          */
/*  Connection connection = getConnection();
            DatabaseMetaData databaseMetaData = connection.getMetaData();
            ResultSet resultSet = databaseMetaData.getColumns(null, "%", tableName, "%");
*//*


            //生成Mapper文件
            generateMapperFile(tableName);
            //生成Dao文件
            generateDaoFile(tableName);
            //生成Repository文件
            generateRepositoryFile(tableName);
            //生成服务层接口文件
            generateServiceInterfaceFile(tableName);
            //生成服务实现层文件
            generateServiceImplFile(tableName);
            //生成Controller层文件
            generateControllerFile(tableName);
            //生成DTO文件
            //generateDTOFile(tableName);
            //生成Model文件
            //generateModelFile(tableName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

        }
    }

    private void generateModelFile(ResultSet resultSet) throws Exception {
*/
/*
        final String suffix = ".java";
        final String path = diskPath + changeTableName + suffix;
        final String templateName = "Model.ftl";
        File mapperFile = new File(path);
        List<ColumnClass> columnClassList = new ArrayList<>();
        ColumnClass columnClass = null;
        while(resultSet.next()){
            //id字段略过
            if(resultSet.getString("COLUMN_NAME").equals("id")) continue;
            columnClass = new ColumnClass();
            //获取字段名称
            columnClass.setColumnName(resultSet.getString("COLUMN_NAME"));
            //获取字段类型
            columnClass.setColumnType(resultSet.getString("TYPE_NAME"));
            //转换字段名称，如 sys_name 变成 SysName
            columnClass.setChangeColumnName(replaceUnderLineAndUpperCase(resultSet.getString("COLUMN_NAME")));
            //字段在数据库的注释
            columnClass.setColumnComment(resultSet.getString("REMARKS"));
            columnClassList.add(columnClass);
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("model_column",columnClassList);
        generateFileByTemplate(templateName,mapperFile,dataMap);*//*


    }

   */
/* private void generateDTOFile(ResultSet resultSet) throws Exception {
        final String suffix = "DTO.java";
        final String path = "D://" + changeTableName + suffix;
        final String templateName = "DTO.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap);
    }*//*


    private void generateControllerFile(String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        final String suffix = "Controller.java";
        final String path = diskPath + changeTableName + suffix;
        final String templateName = "Controller.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap,tableName);
    }

    private void generateServiceImplFile(String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        final String suffix = "ServiceImpl.java";
        final String path = diskPath + changeTableName + suffix;
        final String templateName = "ServiceImpl.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap,tableName);
    }

    private void generateServiceInterfaceFile(String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        final String prefix = "I";
        final String suffix = "Service.java";
        final String path = diskPath + prefix + changeTableName + suffix;
        final String templateName = "Service.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap,tableName);
    }

    private void generateRepositoryFile(String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        final String suffix = "Repository.java";
        final String path = diskPath + changeTableName + suffix;
        final String templateName = "Repository.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap,tableName);
    }

    private void generateDaoFile(String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        final String suffix = "DAO.java";
        final String path = diskPath + changeTableName + suffix;
        final String templateName = "entity.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap,tableName);

    }

    private void generateMapperFile(String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        final String suffix = "Mapper.xml";
        final String path = diskPath + changeTableName + suffix;
        final String templateName = "Mapper.ftl";
        File mapperFile = new File(path);
        Map<String, Object> dataMap = new HashMap<>();
        generateFileByTemplate(templateName, mapperFile, dataMap,tableName);

    }

    private void generateFileByTemplate(final String templateName, File file, Map<String, Object> dataMap,String tableName) throws Exception {
        String changeTableName = replaceUnderLineAndUpperCase(tableName);
        //查询表设置
        QueryWrapper<ViewModule> wrapper = new QueryWrapper<>();
        wrapper.eq("view_maintable", tableName);
        ViewModule viewModule= viewModuleService.getOne(wrapper);

        //查询字段设置
        QueryWrapper<ViewUiproperties> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ui_table", tableName);
        queryWrapper.orderByAsc("ui_order");
        List<ViewUiproperties> list = viewUipropertiesService.list(queryWrapper);


        Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
        FileOutputStream fos = new FileOutputStream(file);
        dataMap.put("table_name_small", tableName);
        dataMap.put("table_name", changeTableName);
        dataMap.put("bussiPackage", changeTableName);
        dataMap.put("entityPackage", changeTableName);
        dataMap.put("entityName", changeTableName);

        dataMap.put("originalColumns", list);

        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
        template.process(dataMap, out);
    }

    public String replaceUnderLineAndUpperCase(String str) {
        StringBuffer sb = new StringBuffer();
        sb.append(str);
        int count = sb.indexOf("_");
        while (count != 0) {
            int num = sb.indexOf("_", count);
            count = num + 1;
            if (num != -1) {
                char ss = sb.charAt(count);
                char ia = (char) (ss - 32);
                sb.replace(count, count + 1, ia + "");
            }
        }
        String result = sb.toString().replaceAll("_", "");
        return StringUtils.capitalize(result);
    }

*/

}
